import * as services from 'services/scale';
import * as familySevices from 'services/family';
import { Toast } from 'antd-mobile';
import { routerRedux } from 'dva/router';
import { SCALE_PHY, SCALE_PRE, SCALE_CHD, SCALE_HYP, SCALE_TCM, SCALE_DIA, SCALE_PARTUM, SCALE_CHD_C, SCALE_PREPRE } from 'const';

export default {
  namespace: 'scale',

  state: {
    url:"",
    records: [],
    detail: {},
    details: {},
    questions: [],
    programerec: [],
    programeint: [],
    // <Michael>
    scalevalue: {},
    mypathname: "",
    recids: [],
    intids: [],
    disabled: true,
    isDisabled: false,  
  },

  reducers: {
    save(state, action) {
      
      return { ...state, ...action.payload };
    },

    savePrograme(state, { payload: { type, value } }) {
      let checktype = "";
      if (type == "programerec") {
        checktype = "recids";
      }
      if (type == "programeint") {
        checktype = "intids"
      }
      const data = state[checktype];
      if (data.indexOf(value) !== -1) {
        data.splice(data.indexOf(value), 1);
      } else {
        data.push(value);
      }
      return {
        ...state,
        [checktype]: data,
      };
    },
  },

  effects: {
    * fetchScaleEva({ payload:{ uid, type }}, { call, put }){

        const detail = yield call(services.queryScaleEva, type, uid);
        yield put({ type: 'save', payload: { detail: detail.data || {} } });
    },

    * fetchScaleDetail({ payload: { uid, type, familyId } }, { call, put }) {
        const detail = yield call(services.queryScaleDetail, type, uid, familyId);// 查看测评详情
        yield put({ type: 'save', payload: { detail: detail.data || {} } });
    },

    * deleteScaleRecord({ payload: uid }, { call, put }) {
      let del = yield call(services.deleteScaleRecord, uid);
      if(del.code == 200){
           Toast.success('删除成功', 2)
       }else{
           Toast.fail(del.message, 2)
       }
    },

    * fetchScaleQuestions({ payload: { type, gender } }, { call, put }) {
      const questions = yield call(services.queryScaleQuestions, { type, gender });
      // if (!questions) { questions = []; }
      // 获取测评题目
      yield put({
        type: 'save',
        payload: { questions },
      });
    },
    * submitQuestions1({payload: { type, patientValue1, patientValue2, patientValue3, ...rest}}, { call, put}){
      let report;
      Toast.loading('正在加载');
      report = yield call(services.submitScaleByUser1, type, rest.patientId, patientValue1, patientValue2, patientValue3)
      yield put({ type: 'save', payload: { report } });
      Toast.success('提交成功',2);
      const ss = "/healthy/scale_record/"+report.data.uid;
      let reports = report.data;
      if (rest.redirectUrl) {
        yield put(
          routerRedux.push({
            pathname: rest.redirectUrl,
            state: {
              title: '2/3',
              type,
              patientvalue,
              jw,
              sc,
              ...reports,
              ...rest,
            },
          }),
        );
      } else {
        const data = yield call(services.queryScaleList);
        yield put({ type: 'save', payload: { records: data.data || [] } });
        yield put(
          routerRedux.replace({
            pathname: ss,
            state: {
              record:{
                ...reports,
                text: '该条记录将保存到测评记录中',
                // type: rest.route.path, 
              },
            }
          }));
        window.scrollTo(0, 0);
      }
    },
    * submitQuestions({ payload: { type, patientValue, jw, sc, ...rest } }, { call, put }) {
        let report;
        Toast.loading('正在加载')
        if( type === 'partum'){
            report = yield call(services.submitScaleByUser, type, rest.patientId, patientValue, jw, sc);
        }else{
            report = yield call(services.submitScaleByUser, type, rest.patientId, patientValue);
        }
        Toast.loading('正在加载')
        yield put({ type: 'save', payload: { report } });
        Toast.success('提交成功',2);
        const ss = "/healthy/scale_record/"+report.data.uid;
        let reports = report.data;
        if (rest.redirectUrl) {
          yield put(
            routerRedux.push({
              pathname: rest.redirectUrl,
              state: {
                title: '2/3',
                type,
                patientvalue,
                jw,
                sc,
                ...reports,
                ...rest,
              },
            }),
          );
        } else {
          const data = yield call(services.queryScaleList);
          yield put({ type: 'save', payload: { records: data.data || [] } });
          yield put(
            routerRedux.replace({
              pathname: ss,
              state: {
                record:{
                  ...reports,
                  text: '该条记录将保存到测评记录中',
                  // type: rest.route.path, 
                },
              }
            }));
          window.scrollTo(0, 0);
          // yield put(routerRedux.replace(`/healthy/scale_record/{report.Uid}`));
        }
    },
    * submitScaleByUsers({ payload: { type, patientValue, jw, sc, hy, height, weight, isReturn, isMiscarriage, isAbortion,...rest } }, { call, put }) {
      let report;
      Toast.loading('正在加载')
      if( type === 'prepre' || type === 'normal'){
          report = yield call(services.submitScaleByUsers, type, rest.patientId, patientValue, jw, sc, hy, height, weight, isReturn, isMiscarriage, isAbortion);
      }
      Toast.loading('正在加载')
      yield put({ type: 'save', payload: { report } });
      Toast.success('提交成功',2);
      const ss = "/healthy/scale_record/"+report.data.uid;
      let reports = report.data;
      if (rest.redirectUrl) {
        yield put(
          routerRedux.push({
            pathname: rest.redirectUrl,
            state: {
              title: '2/3',
              type,
              patientValue,
              jw,
              sc,
              hy,
              height, 
              weight, 
              isReturn, 
              isMiscarriage, 
              isAbortion,
              ...reports,
              ...rest,
            },
          }),
        );
      } else {
        const data = yield call(services.queryScaleList);
        yield put({ type: 'save', payload: { records: data.data || [] } });
        yield put(
          routerRedux.replace({
            pathname: ss,
            state: {
              record:{
                ...reports,
                text: '该条记录将保存到测评记录中',
              },
            }
          }));
        window.scrollTo(0, 0);
      }
    },

    * submitScalePrograme({ payload: { type, ...data } }, { call, put }) {
      const res = yield call(services.submitScalePrograme, type, data, );
      Toast.success('保存成功');
    },

    * reset({ payload }, { call, put }) {
      // return { ...state, payload: { questions: [], scalevalue: {} } };
      yield put({ type: 'save', payload: { questions: [], scalevalue: {} } });
    },

     * pickImg({ payload },{ call, put}){
      const url = yield call(services.pickImg);
      yield put ({type: "save", payload: {url:url.data}});
    }
  },

  subscriptions: {
    setup({ dispatch, history }) {
      // 监听当前的地址变换
      return history.listen((location) => {
        const { pathname, query, href,...rest } = location;
        const sheetType = {
          1: 'old',
          2: 'nine',
          3: 'phy',
          4: 'pre',
          5: 'hyp',
          6: 'chd',
          11: 'dia',
          12: 'tcm',
          13: 'partum',
          14: 'prepre',
          16: 'normal',
          17: 'phy2',
        };
        // banner图显示的解决方案
        if (/healthy$/.test(pathname)){
          // 当路径为healthy的时候和直接为空的时候
          const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
          if (auth) {
            dispatch({type:"pickImg" });
            
          }
          // getItem()作为 Storage 接口的方法，接受一个键名（key name）作为参数，并返回对应键名的值（key's value）。
        }
        // TODO: APP嵌入H5的授权临时解决方案
        if (query.s && query.s === 'app') {
          localStorage.removeItem('auth'+sessionStorage.getItem("hid"));
          sessionStorage.removeItem('token');
          sessionStorage.setItem('token', 'app');
          // removeItem() 作为 Storage 接口的方法，接受一个键名作为参数，会把该键名从存储中移除。
          // setItem() 作为 Storage 接口的方法，接受一个键名和值作为参数，将会把键名添加到存储中，如果键名已存在，则更新其对应的值。
        }

        if (/scale_record$/.test(pathname)) {
          services.queryScaleList().then(n =>{
              dispatch({ type: 'save', payload: { records: n.data || [] } })
          })
        }

        if (/scale_record\/\w+/.test(pathname) ) {
          let record = "", report = "";
          if (rest.state) {
            record = rest.state.record;
            report = rest.state.report;
          }
          let payload = {};
          if(record){
            payload = {
              uid: record.uid,
              type: sheetType[record.eva],
            };
          }
          if(report){
            payload = {
              uid: report.uid,
              type: sheetType[report.eva],
            };
          }
          if(record){
              const auth = JSON.parse(localStorage.getItem("auth"+sessionStorage.getItem("hid")));
              if(record.eva == 16 || record.eva == 14){
                   dispatch({ type: 'fetchScaleEva', payload:{
                    uid:  record.evaUid,
                    type: sheetType[record.eva],
                  }})
               }else{
                   dispatch({ type: 'fetchScaleDetail', payload:{
                    uid:  record.evaUid, 
                    type: sheetType[record.eva],
                    familyId: auth.patientId
                  }});
               }
          }
        }
        if (
          /scale\/\w+\/\d+/.test(pathname) ||
          /native\/scale$/.test(pathname) ||
          /scale_record\/[\w+-]+\/sheet$/.test(pathname) ||
          /archives\/report\/[\w+-]+\/sheet$/.test(pathname) ||
          //<Michael>
          /native\/scale_phy$/.test(pathname) ||
          /native\/scale_pre$/.test(pathname) ||
          /native\/scale_hyp$/.test(pathname) ||
          /native\/scale_chd$/.test(pathname) ||
          /native\/scale_dia$/.test(pathname) ||
          /native\/scale_tcm$/.test(pathname) ||
          /native\/scale_partum$/.test(pathname) ||
          /native\/scale_prepre$/.test(pathname) ||
          /native\/scale_normal$/.test(pathname) ||
          /native\/scale_phy2$/.test(pathname)
        ) {
          let type;
          if (rest.state) {
            if (rest.state.record) {
              type = sheetType[rest.state.record.Eva];
            } else {
              type = rest.state.type;
            }
          }

          type = type || query.type;
          if (/native\/scale_phy$/.test(pathname)) {
            type = 'phy';
          }
          if (/native\/scale_pre$/.test(pathname)) {
            type = 'pre';
          }
          if (/native\/scale_hyp$/.test(pathname)) {
            type = 'hyp';
          }
          if (/native\/scale_chd$/.test(pathname)) {
            type = 'chd';
          }
          if (/native\/scale_dia$/.test(pathname)) {
            type = 'dia';
          }
          if (/native\/scale_tcm$/.test(pathname)) {
            type = 'tcm';
          }
          if (/native\/scale_partum$/.test(pathname)){
            type = 'partum';
          }  
          if (/native\/scale_prepre$/.test(pathname)){
            type = 'prepre';
          }
          if (/native\/scale_normal$/.test(pathname)){
            type = 'normal';
          }
          if (/native\/scale_phy2$/.test(pathname)){
            type = 'phy2';
          }
          if (location.state) {
            if(location.state.report){
              if (location.state.report) {
                if (location.state.report.Eva == 1) {
                  type = "old"
                }
                if (location.state.report.Eva == 2) {
                  type = "nine"
                }
                if (location.state.report.Eva == 3) {
                  type = "phy"
                }
                if (location.state.report.Eva == 4) {
                  type = "pre"
                }
                if (location.state.report.Eva == 5) {
                  type = "hyp"
                }
                if (location.state.report.Eva == 6) {
                  type = "chd"
                }
                if (location.state.report.Eva == 11) {
                  type = "dia"
                }
                if (location.state.report.Eva == 12) {
                  type = "tcm"
                }
                if (location.state.report.Eva == 13) {
                  type = "partum"
                }
                if (location.state.report.Eva == 14) {
                  type = "prepre"
                }
                if (location.state.report.Eva == 16) {
                  type = "normal"
                }
                if (location.state.report.Eva == 17) {
                  type = "phy2"
                }
              }
            }
          }
        }

        if (/scale\/\w+\/\d+/.test(pathname)) {
          dispatch({ type: 'save', payload: { detail: {} } });
        }

        if (/native\/scale$/.test(pathname) || /native\/scale_phy$/.test(pathname) || /native\/scale_phy2$/.test(pathname) || /native\/scale_pre$/.test(pathname) || /native\/scale_hyp$/.test(pathname) || /native\/scale_chd$/.test(pathname) ||/native\/scale_dia$/.test(pathname)||/native\/scale_tcm$/.test(pathname)|| /native\/scale_partum$/.test(pathname) || /native\/scale_normal$/.test(pathname)) {
         dispatch({
            type: 'family/fetchPatient',
            payload: {
              doctorid: query.doctorid,
              patientid: query.memberid,
            },
          });
        }
      });
    },
  },
};
